$(function(){
    var pages = null;
    var ops = $('<div />');
    var opsp = $('<div />');
    opsp.append($('<div />').addClass('bread').css({'padding':'3px','background':'#fafafa','border-bottom':'1px solid #ededed'})).append($('<div />').addClass('folders'));
    var selected_theme = $('<div />').addClass('m-5').css({'padding':'5px','border':'1px solid #CCC','border-radius':'10px','cursor':'pointer'}).insertBefore(
        $('#Page_theme_id').css({'visibility':'hidden','position':'absolute','opacity':'0','left':'-9999px'})
    ).html('<em>Не выбрано</em>');
    var selected_page = $('<div />').addClass('m-5').css({'padding':'5px','border':'1px solid #CCC','border-radius':'10px','cursor':'pointer'}).insertBefore(
        $('#Page_parent_id').css({'visibility':'hidden','position':'absolute','opacity':'0','left':'-9999px'})
    ).html('<em>Верхний уровень</em>');
    $('#Page_theme_id option').each(function(){
        var op = $('<div />').addClass('m-5').css({'padding':'5px','background':'#AAC','cursor':'pointer'});
        op.data('option',$(this));
        if(typeof themes[$(this).attr('value')] !== 'undefined')
            op.append('<img src="'+themes[$(this).attr('value')][1]+'" />');
        op.append($(this).text());
        ops.append(op);
        op.click(function(){
            $('#Page_theme_id').val($(this).data('option').attr('value'));
            selected_theme.html($(this).html());
            $.rusWindows['#theme_select'].close();
        })
        if($(this).is(':selected')){
            selected_theme.html('');
            if(typeof themes[$(this).attr('value')] !== 'undefined')
                selected_theme.append('<img src="'+themes[$(this).attr('value')][1]+'" />');
            selected_theme.append($(this).text());
        }
    });
    
    function drawFolders(x,data){
        var folders = x.find('.folders').html('');
        var bread = x.find('.bread').html('');
        for(i in data){
            var op = $('<div />').addClass('folder-admin');
            op.append(data[i].title);
            op.data({'page':data[i],'pid':i})
            folders.append(op);
            op.dblclick(function(){
                var page = $(this).data('page');
                var pid = $(this).data('pid');
                $.rusWindows['#page_select'].getContent().data('selected',[pid,page.title]);
                if(typeof page['children'] !== 'undefined')
                    drawFolders(x,page['children']);
                else{
                    $.loader();
                    $.get('/page/children',{id:pid},function(m){page['children']=m;drawFolders(x,m);$.loader();},'json');
                }
            });
            op.click(function(){
                var page = $(this).data('page');
                var pid = $(this).data('pid');
                $.rusWindows['#page_select'].getContent().data('selected',[pid,page.title]);
                folders.find('.selected').removeClass('selected');
                $(this).toggleClass('selected');});
        }
    }
    
    //Adding new theme link
    $('<a />').attr({'href':'/theme/add?back='+back_link})
    .html('Добавить тему').insertAfter($('#Page_theme_id'));
    
    selected_page.html($('#Page_parent_id :selected').html());
            
    selected_page.click(function(){
        var x = opsp.clone(true);
        x.css({
            'padding':'10px',
            'background':'#FFF'
        }).attr('id','page_select');
        var foot = $('<div />')
                .append($('<button />').addClass('button').addClass('fright').html('Отменить').click(function(){$.rusWindows['#page_select'].close();}))
                .append($('<button />').addClass('button').html('Применить').click(function(){
                    if(typeof $.rusWindows['#page_select'].getContent().data('selected') != 'undefined'){
                        $('#Page_parent_id').val($.rusWindows['#page_select'].getContent().data('selected')[0]);
                        selected_page.html($.rusWindows['#page_select'].getContent().data('selected')[1]);
                    }
                    $.rusWindows['#page_select'].close();
                }))
        var w = x.rusWindow({modal:true,'title':'Материалы',footer:foot});
        w.setSize(800,600);
        w.getContent().parent().css({left:'50%','margin-left':'-400px'});
        if(pages !== null){
            drawFolders(x,pages);
        }else{
            $.get('/page/children',{id:0},function(m){
                pages=m;
                drawFolders(x,m);
            },'json');
        }
    });
    selected_theme.click(function(){
        var x = ops.clone(true);
        x.css({
            'padding':'10px',
            'background':'#FFF'
        }).attr('id','theme_select');
        var w = x.rusWindow({modal:true,'title':'Тема оформления'});
    });
   
    /**
     * Add remove music
     */
    $('.add_music').live('click',function(){
        $.sfb({select:function(files){
                var tmp = $('#Page_music').val()!=''?$('#Page_music').val().split(','):[];
                for(i in files){
                    var name = files[i].file.split('/').pop() + '::/' + files[i].file;
                    if(tmp.indexOf(name)===-1){
                        tmp.push(name);
                    }
                }
                $('#Page_music').val(tmp.join(','));
                $('body').css('overflow','visible');//sfb fix;
                redraw_musics();
                return true;
            },base:"../../uploads/Music/",maxsize:15728640,plugins:['filetree'],allow:['mp3'],swfupload:true,preview:true,bgcolor:'#CEE9F4',bgalpha:.8});
        return false;
    });
    function redraw_musics(){
        var tmp = $('#Page_music').val()!=''?$('#Page_music').val().split(','):[];
        $('#Page_music_cont').remove();
        var cont = $('<div />').attr('id','Page_music_cont').css({
            'border':'1px solid #cda',
            'padding':'10px'
        });
        for(i in tmp){
            var k = tmp[i].split('::');
            var name = k.shift();
            
            var d = $('<div />')
                    .css({
                        'border':'1px solid #adc',
                        'background':'#fcfcfc',
                        'margin':'5px',
                        'padding':'5px'
                    })
                    .append($('<a href="#" style="float:right" data-im="'+i+'"><img src="/images/cross.png" alt="X" title="Убрать" /></a>').click(function(){
                        var i = $(this).parent().parent().children('div').index($(this).parent());
                        $(this).parent().fadeOut(function(){
                            remove_musics(i);
                            $(this).remove();
                        });
                        return false;
                    }))
                    .append($('<input />').attr({'type':'text','data-im':i}).val(name).change(function(){
                        var tmp = $(this).parent().data('val');
                        var x = tmp.split('::');
                        x[0] = $(this).val();
                        tmp = x.join('::');
                        $(this).parent().data('val',tmp)
                        update_values();
                    })).data('val',tmp[i]);
            cont.append(d);
        }
        cont.sortable({
                        stop:function(e,ui){
                            update_values();
                        }
                    });
        cont.insertAfter($('#Page_music'));
    }
    function update_values(){
        var tmp = [];
        $('#Page_music_cont').children('div').each(function(){
            tmp.push($(this).data('val'));
        });
        $('#Page_music').val(tmp.join(','));
    }
    function remove_musics(i){
        var tmp = $('#Page_music').val().split(',');
        tmp.splice(i,1);
        $('#Page_music').val(tmp.join(','));
    }
    //init musics
    redraw_musics();
    
    //////////////////////////
    //CkEditor WYSIWYG
    //////////////////////////
    if(typeof CKEDITOR.instances['Page_text'] !== 'undefined')
        delete(CKEDITOR.instances['Page_text']);
    CKEDITOR.replace( 'Page_text' , {height:600});
});